<template>
  <TableDivBox :data="data" @searchBtn="searchBtn" :isFull="false" :margin="0" :style="{
    marginBottom: data.search?.pageSize ? '-8px' : '',
  }">
    <template #search="{ search }" v-if="$slots.search">
      <slot name="search" :search="search" />
    </template>
    <template #headR v-if="$slots.headR">
      <slot name="headR" />
    </template>
    <div class="list-b-12">
      <div v-if="isGood && !data.disabled">
        <el-input v-model="goodValue" class="w300" clearable placeholder="请扫码或输入规格编号添加明细" @change="addGood">
          <template #prefix>
            <i class="iconfont icon-scanning"></i>
          </template>
        </el-input>
      </div>
      <ElTableBox :tableId="data.tableId" :maxHeight="data.maxHeight" :tbody="data?.tbody" :height="height"
        :thead="data?.thead" :disabled="data.disabled" :sortKey="data?.sortKey" :sortTitle="data?.sortTitle"
        :selectable="selectable || data.selectable" :search="data?.search" :isHighlight="false"
        :spanMethod="!!data.isColumn ? setSpanMethod : data?.spanMethod" @searchBtn="searchBtn"
        :isRadio="isRadio || typeof data.select === 'function'" :isCheckbox="isCheckbox" v-if="data && tbaleShow"
        @changeBtn="changeBtn" @tableRadioBtn="tableRadioBtn" @onSort="onSort">
        <template #[key]="{ row, index }" v-for="(slot, key) in $slots" :key="key">
          <slot :name="key" :row="row" :index="index" v-if="!keyNotArr.includes(key)" />
        </template>
        <template #operation="{ row, index }" v-if="data?.operation && data.operation.length > 0 && !data.disabled">
          <div class="flex-center-center list-r-8">
            <template v-for="btn in data.operation">
              <IconBox :icon="typeof btn.icon === 'function' ? btn.icon(row) : btn.icon"
                :title="typeof btn.label === 'function' ? btn.label(row) : btn.label"
                v-if="typeof btn.hidden === 'function' ? btn.hidden(row, index) : !btn.hidden"
                @onClick="operationBtn(btn, row, index)" />
            </template>
          </div>
        </template>
      </ElTableBox>
      <template v-if="!data.disabled">
        <SelectCom :isCheckbox="true" :maring="0" :title="data.addSelect?.title" :selectable="(item: any) => {
          const _arr = data.tbody.map((el: any) => el[data.addSelect?.rowKey || data.rowKey])
          return !_arr.includes(item[data.addSelect?.rowKey || data.rowKey] || item.specificationCode)
        }" :search="data.search" @searchBtn="searchBtn" :table="data.addSelect" :type="data.addSelect.type"
          v-if="data.addSelect" @selectBtn="selectBtn">
          <template #search="{ search }" v-if="$slots.search">
            <slot name="search" :search="search" />
          </template>
          <el-button class="wAuto" icon="Plus">添加明细</el-button>
        </SelectCom>
        <el-button class="wAuto" icon="Plus" v-else-if="data.add" @click="addbtn(data.add)">添加明细</el-button>
      </template>
    </div>
  </TableDivBox>
</template>
<script setup lang="ts">
//获取pinia
// import { useUserStore } from '@/store/index';
// const userStores: any = useUserStore();
//获取当前实例
import { getCurrentInstance, onMounted, ref } from 'vue';
const { proxy } = getCurrentInstance() as any;
//获取父级数据
const props = withDefaults(
  defineProps<{
    data?: any; //主数据
    height?: String | Number; //高度
    margin?: number; //间距
    isRadio?: boolean; //单选
    isGood?: boolean; //是否物料
    isCheckbox?: boolean; //单选
    selectable?: Function; //是否禁用
  }>(),
  {
    data: {}
  },
);
watch(() => props.data?.tbody?.length, (newVal, oldVal) => {
  //是否存在合并的key
  if (!!props.data?.columnKey && props.data.tbody) {
    setMerge(props.data.tbody, props.data.columnKey)
  }
  setSort()
});
const tbaleShow = ref(true)
//设置合并数据
const setSpanMethod = (res: any) => {
  const { row, column, rowIndex, columnIndex } = res
  let isColumn = props.data.isColumn.includes(column.property);//需要合并的表头
  if (isColumn && row.rowspan >= 0) {
    // const _text = `${column.property}：${row[column.property]},[行：${row.rowIndex},列：${columnIndex},合并：${row.rowspan}]`;
    if (row.rowspan === 0) {
      return {
        rowspan: 0,
        colspan: 0,
      };
    } else {
      return {
        rowspan: row.rowspan,
        colspan: 1,
      };
    }
  }
};
//设置合并数据
const setMerge = (arr: any, key: string) => {
  if (arr.length === 0) return
  let _rowspan = 1//合并数
  let _rowIndex = 0//合并数
  let _columnKey = ''//型号唯一编号
  arr.forEach((el: any, elIndex: number) => {
    if (_columnKey === el[key]) {
      el.rowspan = 0
      _rowspan++
    } else {
      _columnKey = el[props.data.columnKey]
      _rowIndex = elIndex
      _rowspan = 1
      el.rowspan = 1
    }
    arr[_rowIndex].rowspan = _rowspan//设置
  })
};
//单选数据
const tableRadioBtn = (row: any) => {
  if (typeof props.data.select === 'function') {
    props.data.select(row)
  }
};
const changeBtn = (value: any, row: any, option: any) => {
  if (proxy.$isFunction(props.data.changeBtn)) {
    props.data.changeBtn(value, row, option)
  }
};
const keyNotArr = ref(['search', 'header']);
const goodValue = ref('');
const emit = defineEmits<{
  //fn为父组件引入子组件是定义的子组件事件属性，可随意定义
  (event: 'searchBtn'): void;
  (event: 'onSort'): void;
  (event: 'selectBtn', arr: any): void;
}>();
const searchBtn = () => {
  emit('searchBtn');
};
const selectBtn = (rows: any) => {
  emit('selectBtn', rows);
};
const addGood = (value: string) => {
  if (!!!value) {
    return
  }
  proxy.$api.Goods.GetPageGoodsSpecificationView({
    pageIndex: 1, // 当前页码 (从1开始)
    pageSize: 1, // 每页显示数据的数量
    totalCount: 0, // 总数据数量
    queryDataBaseFiled: "specificationCode", // 关键字查询字段，空值查询全部（如果需要单独设置）
    likeWords: value, // 查询关键字，空值查询全部（如果需要单独设置）
    orderByFiled: "", // 排序字段
    orderByType: 0, // 排序方式，0-倒序,1-升序
    isShowDisabled: -1, // 是否显示禁用,-1：显示所有的；0：仅显示未作废的；1 仅显示作废的
    groupCode: "", // 物料分组编码
    supplierCode: "", // 供应商编码
    state: 1 // 状态:-1:全部；0待确认；1已确认；2已作废
  }).then((res: any) => {
    if (res.list.length > 0) {
      let _obj = proxy.$getNewObj(res.list[0], goodObj.value.goodKey)
      props.data.tbody.push(_obj)
      proxy.$message('添加物料成功')
    } else {
      proxy.$message('未查询到物料', 'error')
    }
    goodValue.value = ''
  });
};
//添加
const addbtn = (add: any) => {
  if (typeof add === 'function') {
    add()
  } else {
    const _row = JSON.parse(JSON.stringify(add))
    props.data.tbody.push(_row)
    setSort()
  }
}
//操作按钮
const operationBtn = (btn: any, row: any, index: number) => {
  let _data = props.data
  switch (btn.label) {
    case '复制':
      if (proxy.$isFunction(btn.click)) {
        btn.click(row, index, setSort)
      } else {
        let _row = JSON.parse(JSON.stringify(row))
        if (proxy.$isArr(btn.notArr)) {
          for (let key in _row) {
            if (btn.notArr.includes(key)) {
              if (proxy.$isArr(_row[key])) {
                _row[key] = []
              } else if (typeof _row[key] === 'number') {
                _row[key] = null
              } else {
                _row[key] = ''
              }
            }
          }
        }
        _data.tbody.splice(index + 1, 0, _row)
        setSort()
      }
      break;
    case '删除':
      if (proxy.$isFunction(btn.click)) {
        btn.click(row, index, setSort)
      } else {
        _data.tbody.splice(index, 1)
        setSort()
      }
      break;
    default:
      if (proxy.$isFunction(btn.click)) {
        btn.click(row, index, setSort)
      }
      break;
  }
};
const onSort = (evt: any) => {
  const _data = props.data;
  const oldIndex = evt.oldIndex;
  const newIndex = evt.newIndex;
  // 获取要移动的项
  const movedItem = _data.tbody[oldIndex];
  // 删除原位置的项
  _data.tbody.splice(oldIndex || 0, 1);
  // 插入到新位置
  _data.tbody.splice(newIndex || 0, 0, movedItem);
  setSort()
  tbaleShow.value = false
  nextTick(() => {
    tbaleShow.value = true
  })
}
const setSort = () => {
  let _data = props.data
  if (_data?.sortKey && _data?.tbody?.length > 0) {
    _data.tbody.forEach((el: any, index: number) => {
      el[_data.sortKey] = index + 1
    })
  }
  emit('onSort');
}
//多选

onMounted(() => {
  setSort()
});
</script>
<style scoped lang="scss"></style>
